package net.zjitc.servlet.log;

import net.zjitc.daomain.User;
import net.zjitc.service.UserService;
import net.zjitc.service.UserServiceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * Created by hasee on 2017/9/27.
 */
@WebServlet(name = "LoginServlet",urlPatterns = "/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserService userService = new UserServiceImpl();
        User user = new User();
        try {
            user = userService.login(username,password);
            request.getSession().setAttribute("user",user);//记录登陆信息
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if(user==null){
            String error = "用户名或密码错误";
            request.setAttribute("error",error);
            request.getRequestDispatcher("/log/login.jsp").forward(request,response);
        }
        if(user!=null){
            request.getSession().setAttribute("user",user);
            response.addCookie(new Cookie("username",user.getUsername()));
            response.sendRedirect("/web/log/success.jsp");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
